package com.opengl.camera;

import java.io.IOException;

import android.annotation.SuppressLint;
import android.content.Context;
import android.hardware.Camera;
import android.opengl.GLSurfaceView;
import android.view.SurfaceHolder;

@SuppressLint("ViewConstructor")
/**
 * This class handles the the camera by handling the camera preview callback.
 * It has controls to open and close the camera as well as the previewcallback function.
 * It receives camera parameters via the CameraParams class (camera preview size). 
 * @author schu
 *
 */
public class CameraPreview extends GLSurfaceView implements SurfaceHolder.Callback
{
	CameraGLSurfaceView m_camgl;
	SurfaceHolder m_holder;
	Camera m_camera;
	
	public CameraPreview(Context context, CameraGLSurfaceView camgl) {
		super(context);
		
		m_camgl = camgl;
		
        // Install a SurfaceHolder.Callback so we get notified when the
        // underlying surface is created and destroyed.
        m_holder = camgl.getHolder();
        m_holder.addCallback(camgl);
        //m_holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
	}
	
	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,	int height) {
		try {
			m_camera.setPreviewDisplay(holder);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		m_camera.startPreview();
		//m_camera.setPreviewCallbackWithBuffer(m_camgl);			
		m_camera.setPreviewCallback(m_camgl);
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		openCamera();		
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		// Surface will be destroyed when we return, so stop the preview.
		// Because the CameraDevice object is not a shared resource, it's very
		// important to release it when the activity is paused.
		closeCamera();	
	}
	
	@Override
	public void onPause()
	{
		closeCamera();
	}
	
	@Override
	public void onResume()
	{
        m_holder = m_camgl.getHolder();
        m_holder.addCallback(m_camgl);	
	}
	
	/**
	 * Closes the camera and stops the preview
	 */
	private void closeCamera()
	{
		try 
		{
			if (m_camera!=null)
			{
				m_camera.stopPreview(); 
				m_camera.setPreviewCallback(null);
				m_camera.release();
				m_camera = null;
			}
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}
	}

	/**
	 * Opens the camera and sets the preview callback
	 */
	private void openCamera()
	{
		if(m_camera == null) m_camera = Camera.open();
		Camera.Parameters p = m_camera.getParameters();  
		p.setPreviewSize(CameraParams.cameraSize.x, CameraParams.cameraSize.y);
		m_camera.setParameters(p);
		
		// store the camera parameters
		CameraParams.cameraParams = m_camera.getParameters();	
	}
}
